// ignore_for_file: argument_type_not_assignable_to_error_handler

import 'dart:async';
import 'dart:convert';
import 'package:eh_mobile/common/store/index.dart';
import 'package:eh_mobile/global.dart';
import 'package:flutter_webrtc/flutter_webrtc.dart';
import 'package:get/get.dart';
import 'package:logger/logger.dart';
import 'package:web_socket_channel/io.dart';

import '../routers/route_names.dart';

class WebSocketState {
  // late String socketUrl;
  late IOWebSocketChannel webSocket;
  bool socketStatus = false;
  late Map<String, dynamic> webSocketResult;
  late bool isError;
  late bool heartStatus;
  late String ip;
  late String mobileIdentity; //手机身份唯一标识
  String get socketUrl =>
      'wss://$ip/ws/$mobileIdentity'; //ws = new WebSocket(`wss://eh-api.touchsprite.com/mobile/ws/${mobile_identity}`);
  int socketClientTime = 5; //心跳发送间隔
}

class WebSocketChannel {
  static final WebSocketChannel instance = WebSocketChannel._internal();

  factory WebSocketChannel() {
    return instance;
  }

  WebSocketChannel._internal();

  final WebSocketState _state = WebSocketState();
  final Logger _logger = Logger();
  late Timer _hearTimer;

  // 连接websocket
  Future connectSocket(String ip, String mobileIdentity) async {
    // 校验连接是否重复
    // if (validConnection(ip, mobileIdentity)) {
    //   _logger.e('websocket重复连接');
    // }
    _state.ip = ip;
    _state.mobileIdentity = mobileIdentity;
    _state.heartStatus = false;
    String socketUrl = _state.socketUrl;
    _logger.d('+++$socketUrl');
    closeSocket().then((value) async {
      _state.webSocket = IOWebSocketChannel.connect(socketUrl);
      _state.socketStatus = true;
      // 开启消息监听
      try {
        _onMessageListener();
      } catch (e) {
        _logger.d('异常$e');
      }

      // 启动发送心跳包
      _heartPacket();
      _logger.d("发起WebSocket请求，地址为：$socketUrl");
    });
  }

  // 重新连接websocket
  void reconnectSocket() {
    _destroyHeart();
    connectSocket(_state.ip, _state.mobileIdentity);
  }

  // 发送websocket消息
  void sendMessage(Map socketMsg) {
    // 如果是连接状态发送消息
    // if (_state.socketStatus) {
    var jsonData = json.encode(socketMsg);
    _state.webSocket.sink.add(jsonData);
    _logger.d('socket发送消息给远端:$jsonData');
    // }
  }

  // 校验连接配置是否重复
  bool validConnection(String ip, String mobileIdentity) {
    return _state.ip == ip && (_state.mobileIdentity == mobileIdentity);
  }

  // WebSocket消息监听器
  void _onMessageListener() {
    _state.webSocket.stream.listen((data) {
      _logger.d('收到远端流stream:$data');
      if (data != null) {
        var jsonData = json.decode(data);
        if (jsonData is Map) {
          String type = jsonData['type'];
          //检测到心跳包
          if (type == 'answer') {
            Map descMap = jsonData['desc'];
            if (descMap.isNotEmpty) {
              RTCSessionDescription description =
                  RTCSessionDescription(descMap['sdp'], descMap['type']);
              Global.webRtcChannel.sendPeer!.setRemoteDescription(description);
            }
          }

          if (type == 'candidate') {
            Map candidateMap = jsonData['candidate'];
            if (candidateMap.isNotEmpty) {
              _logger.d('收到candidate:$candidateMap');
              RTCIceCandidate iceCandidate = RTCIceCandidate(
                  candidateMap['candidate'],
                  candidateMap['sdpMid'],
                  candidateMap['sdpMLineIndex']);
              Global.webRtcChannel.sendPeer!.addCandidate(iceCandidate);
            }
          }

          if (type == 'unpair') {
            closeSocket();
            UserStore().saveBindPhone(false);
            Get.offAllNamed(RouteNames.LOGIN);
          }
        }
      }
    }, onDone: () {
      //结束！
      _state.socketStatus = false;
      _state.isError = true;
    }, onError: (e) {
      //异常！
      _state.socketStatus = false;
    });
  }

  // 销毁心跳包
  void _destroyHeart() {
    if (_state.heartStatus) {
      _hearTimer.cancel();
      _state.heartStatus = false;
    }
  }

  // 发送心跳包
  void _sendHeartPacket() {
    Map<String, dynamic> data = {
      "code": 9999,
      "msg": "心跳包",
    };
    var jsonData = json.encode(data);
    _state.webSocket.sink.add(jsonData);
    _state.heartStatus = true;
  }

  // WebSocket启动心跳包
  void _heartPacket() {
    if (_state.socketStatus) {
      // _hearTimer = Timer.periodic(Duration(seconds: _state.socketClientTime),(timer){
      //    //每隔一段时间就发送心跳包默认5秒
      //    print('_heartPacket发送心跳包');
      //    _sendHeartPacket();
      //  });
    }
  }

  //关闭WebSocket
  Future closeSocket() async {
    // 如果是连接状态
    if (_state.socketStatus) {
      await _state.webSocket.sink.close();
      // state.webSocket = null;
      _state.socketStatus = false;
      _destroyHeart();
    }
  }
}
